//
//  SinaManager.m
//  6p
//
//  Created by weienjie on 15/3/2.
//  Copyright (c) 2015年 fenfen. All rights reserved.
//

#import "SinaManager.h"
//#import "CommonHeader.h"
//#import "CustomTools.h"
#import "WeiboUser.h"
#import "LoginManager.h"
#import "AppDelegate.h"
//#import "BaseViewController.h"
//#import "CollectionObject.h"
//#import "GroupObject.h"

#define kUserID                 @"sina_userid"
#define kSina_AccessToken       @"sina_accessToken"
#define kSina_ExpireDate        @"sina_expireDate"

static SinaManager *intance = nil;

@implementation SinaManager

//单例
+ (id)sharedInstance
{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken,^{intance = [[SinaManager alloc] init];});
    
    return intance;
}

+(id)alloc
{
    if (!intance)
    {
        return [super alloc];
    }
    return [self sharedInstance];
}

- (id)init
{
    if (self = [super init])
    {
        [self readSinaAuthorizInfo];
    }
    return self;
}
- (BOOL)isSinaAuthorizeExpired
{
    if (!self.sina_ExpirationDate || [[NSDate date] timeIntervalSince1970] > [self.sina_ExpirationDate timeIntervalSince1970])
    {
        // force to log out
        self.sina_AccessToken = nil;
        self.sina_ExpirationDate = nil;
        self.sina_UserID = nil;
        return YES;
    }
    return NO;
}

//保存新浪授权信息
- (void)saveSinaAuthorizInfo
{
    if (![self isSinaAuthorizeExpired])
    {
        [[NSUserDefaults standardUserDefaults] setObject:self.sina_UserID forKey:kUserID];
        [[NSUserDefaults standardUserDefaults] setObject:self.sina_AccessToken forKey:kSina_AccessToken];
        [[NSUserDefaults standardUserDefaults] setObject:self.sina_ExpirationDate forKey:kSina_ExpireDate];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

//读取保存的新浪授权信息
- (void)readSinaAuthorizInfo
{
    self.sina_UserID = [[NSUserDefaults standardUserDefaults] objectForKey:kUserID];
    self.sina_AccessToken = [[NSUserDefaults standardUserDefaults] objectForKey:kSina_AccessToken];
    self.sina_ExpirationDate = [[NSUserDefaults standardUserDefaults] objectForKey:kSina_ExpireDate];
}

//清除新浪授权信息
- (void)clearSinaAuthorizInfo
{
    self.sina_UserID = nil;
    self.sina_AccessToken = nil;
    self.sina_ExpirationDate = nil;
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserID];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSina_AccessToken];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSina_ExpireDate];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


#pragma mark - Sina
//新浪授权
- (void)sinaAuthFrom:(NSString *)from
{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURI;
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": from};
    [WeiboSDK sendRequest:request];
    
    
}

//绑定、解除绑定微博
- (void)bindOrRemoveBindWeibo
{
    if ([self isSinaAuthorizeExpired])
    {
        [self sinaAuthFrom:@"bindsina"];
    }
    else
    {
        UIAlertView *alter=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"解除绑定新浪微博?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alter.tag=111;
        [alter show];
    }
}
//分享到新浪
- (void)shareToSina:(id)data
{
    if ([self isSinaAuthorizeExpired])
    {
        [self sinaAuthFrom:@"sinaShare"];
    }
    else
    {
        WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
        authRequest.redirectURI = kRedirectURI;
        authRequest.scope = @"all";
        
//        WBMessageObject *object = [[WBMessageObject alloc]init];
//        
//        if ([data isKindOfClass:[CollectionItem class]]) {
//            WBVideoObject *media = [WBVideoObject object];
//            object.mediaObject = media;
//            
//            CollectionItem *item = (CollectionItem *)data;
//            media.videoUrl = item.url;
//            media.title = item.title;
//            media.thumbnailData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:item.video_img]];
//            
//             object.text = item.content;
//            
//        }
//        else if ([data isKindOfClass:[GroupItem class]])
//        {
//            
//            WBImageObject *imageObject = [WBImageObject object];
//            object.imageObject  = imageObject;
//            
//            GroupItem *item = (GroupItem *)data;
//            imageObject.imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:item.image]];
//            
//            
//            object.text = item.content;
//
//        }
        

        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:data authInfo:authRequest access_token:[[SinaManager sharedInstance] sina_AccessToken]];
        request.userInfo = @{@"ShareMessageFrom": NSStringFromClass([self class])};
        [WeiboSDK sendRequest:request];
    }
}

//新浪推出登录
- (void)sinaLogout
{
    [WeiboSDK logOutWithToken:self.sina_AccessToken delegate:self withTag:nil];
    [self clearSinaAuthorizInfo];
}

//登录新浪
- (void)sinaLogin
{
    //重新授权
    [self sinaAuthFrom:@"sinaLogin"];
}

//新浪自动登录
- (void)sinaAutoLogin
{
    NSDictionary *dict = @{@"sex":@"", @"nickname":@"", @"city":@"", @"headimgurl":@"", @"province":@""};
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"json data:%@",json);
    
    NSMutableDictionary *pra = [NSMutableDictionary dictionary];
    [pra setValue:@"sina" forKey:@"type"];
    [pra setValue:self.sina_UserID forKey:@"openid"];
    [pra setValue:json forKey:@"info"];
    [pra setValue:self.sina_AccessToken forKey:@"access_token"];
    
    [LoginManager loginWithData:pra type:LoginType_sina];
}

//第三方登录，此时需要获取用户第三方信息
- (void)getSina_UserInfo
{
    
    [WBHttpRequest requestForUserProfile:self.sina_UserID withAccessToken:self.sina_AccessToken andOtherProperties:nil queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error){
        NSLog(@"result :%@",result);
        //
        
        NSString *nickname = [(WeiboUser*)result screenName];
        NSString *gender = [(WeiboUser*)result gender];
        NSString *location = [(WeiboUser*)result location];
        NSString *headimgurl = [(WeiboUser*)result profileImageUrl];
        if ([gender isEqualToString:@"m"])
        {
            gender = @"1";
        }
        else
        {
            gender = @"0";
        }

        NSDictionary *dict = @{@"sex":gender, @"nickname":nickname, @"city":location, @"headimgurl":headimgurl, @"province":@"", @"unionid":@"", @"openid":self.sina_UserID, @"privilege":@"", @"province":@"", @"language":@"zh_CN", @"country":@"CN"};
        NSError *err;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&err];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        NSLog(@"json data:%@",json);
        
        NSMutableDictionary *pra = [NSMutableDictionary dictionaryWithDictionary:dict];
        [pra setValue:self.sina_UserID forKey:@"user_unique_id"];
        [pra setValue:self.sina_AccessToken forKey:@"access_token"];

        [LoginManager loginWithData:pra type:LoginType_sina];
    }];

}


#pragma mark - WeiboSDKDelegate
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
}
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        if (response.statusCode == 0)
        {
            [self setSina_UserID:[(WBAuthorizeResponse*)response userID]];
            [self setSina_AccessToken:[(WBAuthorizeResponse*)response accessToken]];
            [self setSina_ExpirationDate:[(WBAuthorizeResponse*)response expirationDate]];
            [self saveSinaAuthorizInfo];
            
            //判断是登录授权，还是分享授权
            NSString *ssofrom = [response.requestUserInfo objectForKey:@"SSO_From"];
            if ([ssofrom isEqualToString:@"sinaLogin"])
            {
//                [CustomTools showWithStatus:@"登录中..."];
                [self getSina_UserInfo];
            }
            else if ([ssofrom isEqualToString:@"sinaShare"])
            {
                
            }
            else if ([ssofrom isEqualToString:@"bindsina"])
            {
//                [[(BaseViewController *)VisibleViewController baseTableView] reloadData];
            }
        }
        else if(response.statusCode != -1)
        {
//            [CustomTools showTipViewWithText:@"认证失败"];
        }
    }
    else if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        if (response.statusCode == 0)
        {
//            [CustomTools showTipViewWithText:@"分享成功"];
        }
        else if(response.statusCode != -1)
        {
//            [CustomTools showTipViewWithText:@"分享失败"];
        }
    }
}


#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 123456 && buttonIndex == alertView.cancelButtonIndex)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[WeiboSDK getWeiboAppInstallUrl]]];
    }
    else if (alertView.tag == 111 && buttonIndex == alertView.cancelButtonIndex)
    {
        [self sinaLogout];
//        [[(BaseViewController *)VisibleViewController baseTableView] reloadData];
    }
}

@end
